import React from 'react';
import { history } from 'umi';
import { Form, Input, Button, message } from 'antd';
import { formatMessage } from 'umi';
import { useRequest } from '@/hooks';
import { editPassword } from '@/services/user';
// import { logout } from '@/services/api';
import { clearLoginStates } from '@/utils/utils';
import PopoverPasswordInput from '@/components/PopoverPasswordInput';
import { size } from 'lodash';
import styles from './index.less';

/**
 * 修改密码
 */
const ChangePassword = ({ form }) => {
    const { getFieldDecorator } = form;

    const { loading: changePwdLoading, run: runChangePwd } = useRequest(params => editPassword(params), {
        manual: true
    });

    const checkConfirm = (rule, value, callback) => {
        if (value) {
            const tempValue = value.trim();
            const password = form.getFieldValue('newPassword').trim();
            if (tempValue === password) {
                callback();
            } else {
                callback(formatMessage({ id: 'validation.password.twice' }));
            }
        }
        callback();
    };

    // const { run: runLogout } = useRequest(() => logout(), {
    //     manual: true
    // });

    const handleClick = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const { code, msg } = await runChangePwd(values);
                switch (code) {
                    case 10000: {
                        message.success(msg);
                        // const logoutResult = await runLogout();
                        // if (logoutResult?.code === 10000) {
                        //     clearLoginStates();
                        //     history.push('/user/login');
                        // }
                        clearLoginStates();
                        history.push('/user/login');
                        break;
                    }
                    case 20011: {
                        message.error('不能频繁重置密码');
                        break;
                    }
                    case 20012: {
                        message.error('旧密码不正确');
                        break;
                    }
                    case 10201: {
                        message.error('密码需包含大小写字母、数字，长度在8-20位');
                        break;
                    }
                    default: {
                        message.error(msg);
                        break;
                    }
                }
            }
        });
    };

    return (
        <div className={styles.changePasswordWrapper}>
            <section>
                <Form labelCol={{ span: 4, offset: 3 }} wrapperCol={{ span: 12 }}>
                    <Form.Item
                        label={formatMessage({
                            id: 'form.oldPassword.label'
                        })}
                    >
                        {getFieldDecorator('password', {
                            rules: [
                                {
                                    required: true,
                                    message: formatMessage({
                                        id: 'form.oldPassword.placeholder'
                                    })
                                }
                            ]
                        })(
                            <Input.Password
                                placeholder={formatMessage({
                                    id: 'form.oldPassword.placeholder'
                                })}
                            />
                        )}
                    </Form.Item>
                    <Form.Item
                        className="noErrorStyle"
                        label={formatMessage({
                            id: 'form.newPassword.label'
                        })}
                    >
                        {getFieldDecorator('newPassword', {
                            rules: [
                                {
                                    required: true
                                },
                                {
                                    validator(rule, value, callback) {
                                        const tempValue = value?.trim();
                                        if (tempValue && (tempValue.length < 8 || tempValue.length > 20)) {
                                            callback(
                                                formatMessage({
                                                    id: 'form.passwordRuleStep1.validate'
                                                })
                                            );
                                        } else if (!/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(tempValue)) {
                                            callback(
                                                formatMessage({
                                                    id: 'form.passwordRuleStep2.validate'
                                                })
                                            );
                                        }
                                        callback();
                                    }
                                }
                            ]
                        })(
                            <PopoverPasswordInput
                                onChange={e => {
                                    // 关联校验
                                    const pwdIsError = form.getFieldError('newPassword');
                                    const tempvalue = form.getFieldValue('confirmNewPassword')?.trim();
                                    if (size(pwdIsError) === 0 && tempvalue && tempvalue !== e.target.value?.trim()) {
                                        form.validateFields(['confirmNewPassword']);
                                    }
                                }}
                                checkList={() => {
                                    const value = form.getFieldValue('newPassword')?.trim();
                                    const arr = [];
                                    if (value) {
                                        if (value.length >= 8 && value.length <= 20) {
                                            arr.push(
                                                formatMessage({
                                                    id: 'form.passwordRuleStep1.validate'
                                                })
                                            );
                                        }
                                        if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(value)) {
                                            arr.push(
                                                formatMessage({
                                                    id: 'form.passwordRuleStep2.validate'
                                                })
                                            );
                                        }
                                    }
                                    return arr;
                                }}
                            />
                        )}
                    </Form.Item>

                    <Form.Item
                        label={formatMessage({
                            id: 'form.confirmPassword.label'
                        })}
                    >
                        {getFieldDecorator('confirmNewPassword', {
                            rules: [
                                {
                                    required: true,
                                    message: formatMessage({
                                        id: 'form.newPassword.placeholder'
                                    })
                                },
                                {
                                    validator: checkConfirm
                                }
                            ]
                        })(
                            <Input.Password
                                placeholder={formatMessage({
                                    id: 'form.newPassword.placeholder'
                                })}
                            />
                        )}
                    </Form.Item>
                </Form>
            </section>
            <footer className={styles.footerButton}>
                <Button type="primary" onClick={handleClick} disabled={changePwdLoading} size="large">
                    确定
                </Button>
            </footer>
        </div>
    );
};

export default Form.create()(ChangePassword);
